import { saveRecordInitAssignAccount } from '@/services/api/api-instruct-record';
import ProForm, { DrawerForm, ProFormInstance, ProFormSelect } from '@ant-design/pro-form';
import {Cascader, Input, Space, Spin, Tag, TreeDataNode } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { useMemo, useState } from 'react';
import './index.less';
import { trimStr } from '@/utils/tool';
const { Search } = Input;
interface AssignAccountProps {
  formRef: ProFormInstance | undefined;
  visibleAssign: boolean;
  assignsAccounts: UserData.OrganizationOption[];
  onSave: () => void;
  setVisibleReadReauest: () => void;
  setaccountsLenght: () => void;
}
const getParentKey = (key: React.Key, tree: TreeDataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};
const AssignAccount: React.FC<AssignAccountProps> = ({
  formRef,
  visibleAssign,
  assignsAccounts,
  onSave,
  setVisibleReadReauest,
  setaccountsLenght,
}) => {
  const [loading, setLoading] = useState(false);

  const [dataTreeAccount, setDataTreeAccountState] = useState<DataNode[]>([]);
  const [dataCheckTreeAccount, setDataCheckTreeAccountState] = useState<any>();

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [dataTreeAddress, setDataTreeAddressState] = useState<DataNode[]>([]);
  const [dataLoaded, setDataLoaded] = useState(false);
  // const [dataCheckTreeAccount, setDataCheckTreeAccountState] = useState<any>();

  /**
   * 已经添加的用户列表
   */
  const [targetKeys, setTargetKeyss] = useState<string[]>([]);
  const dataList: { key: React.Key; title: string }[] = [];
  const generateList1 = (data: TreeDataNode[]) => {
    for (let i = 0; i < data?.length; i++) {
      const node = data[i];
      const { key, title } = node;
      dataList.push({ key, title });
      if (node.children) {
        generateList1(node.children);
      }
    }
  };
  generateList1(dataTreeAccount);

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAccountData(data: Array<UserData.Organization>): DataNode[] {
    const treeData = new Array();

    if (data) {
      data.forEach((val, idx, array) => {
        treeData.push({
          title: val.name,
          key: val.id,
          marks: val.marks,
          children: readyTreeAccountData(val.children as Array<UserData.Organization>),
        });
      });
    }
    return treeData;
  }
  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setInputValue(value);
  };
  const onSearch = (val) => {
    const e = trimStr(val)
    if (e === '') {
      setAutoExpandParent(false);
      setExpandedKeys([]);
    } else {
      const newExpandedKeys = dataList
        .map((item) => {
          if (item.title.indexOf(e) > -1) {
            return getParentKey(item.key, dataTreeAccount);
          }
          return null;
        })
        .filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
      setExpandedKeys(newExpandedKeys);
      setAutoExpandParent(true);
    }
    setSearchValue(e);
  };
  /**
   * 加载组织树请求网络
   */
  const loadAccountTreeAccountData = async () => {
    try {
      setLoading(true);
      const response = await saveRecordInitAssignAccount();
      if (response.code === 0) {
        setDataTreeAccountState(readyTreeAccountData(response.data));
      }
      setLoading(false);
    } catch (error) { }
  };

  const treeData = useMemo(() => {
    const loop = (data: TreeDataNode[]): TreeDataNode[] =>
      data.map((item) => {
        const strTitle = item.title as string;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);

        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
              {item?.marks && item?.marks.length > 0 && (
                <Space wrap>
                  {item?.marks.map((item) => (
                    <Tag bordered={false} color="orange">
                      {item}
                    </Tag>
                  ))}
                </Space>
              )}
            </span>
          ) : (
            <>
              <span>{strTitle}</span>
              {item?.marks && item?.marks.length > 0 && searchValue && (
                <Space wrap>
                  {item?.marks.map((item) => (
                    <Tag bordered={false} color="orange">
                      {item}
                    </Tag>
                  ))}
                </Space>
              )}
            </>
          );
        if (item.children) {
          return { title, key: item.key, children: loop(item.children) };
        }

        return {
          title,
          key: item.key,
        };
      });

    return loop(dataTreeAccount);
  }, [dataTreeAccount, searchValue]);

  return (
    <ProForm.Group
      style={{
        display: visibleAssign ? 'block' : 'none',
      }}
    >
      <ProFormSelect
        name="assignAccounts"
        label="已选"
        width='900px'
        showSearch
        hidden={!visibleAssign}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,
          showSearch: true,
          open: false,
          optionFilterProp: 'children',
          filterOption: (input: any, option: any) => {
            if (option.label) {
              return option.label.includes(input);
            }
          },
          showCheckedStrategy: Cascader.SHOW_CHILD,
          listHeight: 500,
          style: {
            marginLeft: '28px',
          },
        }}
        onChange={(value) => {
          console.log(value);
          setaccountsLenght(value.length);
          if (value?.length === 0) {
            onSave(false);
            // formRef?.current?.setFieldsValue({
            //   completeType: '1',
            // });
            setVisibleReadReauest(false);
          }
        }}
        rules={[{ required: visibleAssign, message: '请选择至少一个联络人' }]}
        options={assignsAccounts}
        addonAfter={
          <DrawerForm
            width="500px"
            title="发布范围：通讯录（多选）"
            trigger={
              <a key="activeSaveAssign" onClick={() => { }}>
                点击添加
              </a>
            }
            autoFocusFirstInput
            drawerProps={{
              destroyOnClose: true,
            }}
            onOpenChange={(visible: boolean) => {
              if (visible) {
                loadAccountTreeAccountData();
                console.log(formRef?.current?.getFieldValue('assignAccounts'));
                
                setDataCheckTreeAccountState(formRef?.current?.getFieldValue('assignAccounts'));
              } else {
                setInputValue('');
                setExpandedKeys([]);
              }
              formRef?.current?.setFieldsValue({
                countRead: formRef?.current?.getFieldValue('assignAccounts')?.length,
              });
            }}
            submitter={false}
            onFinish={async (values) => { }}
          >
            <Spin spinning={loading}>
              <Search
                style={{ marginBottom: 8 }}
                placeholder="输入名称查询"
                onChange={onChange}
                value={inputValue}
                onSearch={onSearch}
                allowClear
              />
              {dataTreeAccount && dataTreeAccount.length ? (
                <Tree
                  onExpand={onExpand}
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent}
                  treeData={treeData}
                  checkedKeys={dataCheckTreeAccount}
                  checkable
                  onCheck={(checkedKeys, e) => {
                    const checkKeys = new Array();
                    e.checkedNodesPositions?.forEach((item) => {
                      if (item.node.children?.length === 0) {
                        checkKeys.push(item.node.key);
                      }
                    });
                    setDataCheckTreeAccountState(checkedKeys);
                    console.log(checkKeys);
                    if (checkKeys.length > 0) {
                      onSave(true);
                    } else {
                      onSave(false);
                    }
                    setaccountsLenght(checkKeys.length);
                    formRef?.current?.setFieldsValue({
                      assignAccounts: checkKeys,
                    });
                  }}
                />
              ) : (
                '暂无数据'
              )}
            </Spin>
          </DrawerForm>
        }
      />
    </ProForm.Group>
  );
};

export default AssignAccount;
